package com.asiainfo.indb.view;

import com.asiainfo.indb.PanelUtil;
import com.asiainfo.indb.control.InDbService;
import com.asiainfo.indb.control.InDbServiceLoader;
import com.asiainfo.indb.control.LogService;
import com.asiainfo.indb.control.ThreadFactory;
import com.asiainfo.indb.model.InDbGather;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author zym
 * @date 2019-10-17 22:48
 */
public class SubmitPanel extends BaseInDbPanel implements ActionListener {

    /**
     * 数据收集器
     */
    private InDbGather gather;

    public SubmitPanel(InDbPanel parentPanel) {
        super(parentPanel);

        this.gather = new InDbGather();
    }

    @Override
    public void render() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

        JPanel panel = new JPanel(new BorderLayout());
        JButton submit = new JButton("开始");
        submit.setPreferredSize(new Dimension(submit.getPreferredSize().width, 30));
        submit.setBackground(Color.BLUE);
        submit.addActionListener(this);
        panel.add(submit, BorderLayout.CENTER);

        add(panel, BorderLayout.CENTER);

        setPreferredSize(new Dimension(getParentPanel().getWidth(), getPanelHeight(panel)));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (gather() != null) {
            // 收集数据成功
            // 开始真正的入库逻辑
            // 入库界面渲染
            final InDbService service = InDbServiceLoader.loadService(this.gather);
            final LogService logService = new LogService(service);

            // 入库
            ThreadFactory.run("InDbService", () -> {
                try {
                    service.indb(this.gather, logService);
                } catch (Exception ee) {
                    PanelUtil.error(getTopContainer(), "入库异常：" + ee.getMessage());
                }
            });
        }
    }

    @Override
    public InDbGather gather() {
        if (gather(FilePanel.class) && gather(ControlPanel.class)
                && gather(DbPanel.class) && gather(TablePanel.class)) {
            return this.gather;
        }

        return null;
    }

    /**
     * 收集面板数据
     *
     * @param type 面板类型
     * @return 是否收集成功
     */
    private boolean gather(Class<? extends InDbPanel> type) {
        if (type != null) {
            InDbPanel panel = getCachedPanel(type);
            if (panel != null) {
                InDbGather inDbGather = panel.gather();
                if (inDbGather != null && inDbGather.size() > 0) {
                    this.gather.merge(inDbGather);
                    return true;
                }
            }
        }

        return false;
    }
}
